<?php

namespace App\Http\Controllers;

use App\Http\Resources\OnlineUserResource;
use App\Http\Traits\CheckPermission;
use App\Models\OnlineUser;
use App\Models\Permission;
use App\Services\TokenService;
use Illuminate\Http\Request;

class OnlineUserController extends Controller
{
    use CheckPermission;

    protected $tokenService;
    protected $resource = 'online_users';

    public function __construct(TokenService $tokenService)
    {
        $this->tokenService = $tokenService;
        $this->middleware('auth.api');
    }

    public function index(Request $request)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        // 先更新所有在线用户的在线时长
        try {
            OnlineUser::whereNotNull('login_at')->chunk(100, function ($onlineUsers) {
                foreach ($onlineUsers as $onlineUser) {
                    $onlineUser->updateOnlineDuration();
                }
            });
        } catch (\Exception $e) {
            \Log::warning('批量更新在线时长失败: ' . $e->getMessage());
        }

        $query = OnlineUser::with('user');

        if ($request->filled('username')) {
            $query->where('username', 'like', '%' . $request->username . '%');
        }

        $users = $query->orderBy('last_activity_at', 'desc')
            ->paginate($this->getPageSize($request));

        // 使用Resource格式化分页数据，包括时间字段
        $users->setCollection(
            $users->getCollection()->map(function ($user) {
                return (new OnlineUserResource($user))->resolve(request());
            })
        );

        return $this->success($users, '获取成功');
    }

    public function forceLogout(OnlineUser $onlineUser)
    {
        // 检查分配权限（强制登出）
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_ASSIGN);

        $this->tokenService->removeAll($onlineUser->user_id);
        OnlineUser::where('user_id', $onlineUser->user_id)->delete();

        return $this->success(null, '强制登出成功');
    }
}

